package com.pms.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.AreaCn;
import com.pms.entity.BaseAgency;
import com.pms.entity.BaseModel;
import com.pms.exception.R;
import com.pms.service.IAreaCnService;
import com.pms.service.IBaseAgencyService;
import com.pms.util.PhoneUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 机构类型-1平台2自来水公司3物业4设备厂家5水司分区6物业社区
 */
@RestController
@RequestMapping("baseAgency")
public class BaseAgencyController extends BaseController {
    @Autowired
    IBaseAgencyService baseAgencyService;
    @Autowired
    IAreaCnService areaCnService;
    /**
     * 添加机构
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name="agencyName",value="机构名称",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="agencyType",value="机构类型",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="parentId",value="上级机构id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="agencyPhone",value="机构电话",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="agencyImg",value="机构主图",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="areaGb",value="机构所在地址区编码",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="areaLongitude",value="机构所在地址-经度值",required = false,dataType = "double",paramType="form"),
            @ApiImplicitParam(name="areaLatitude",value="机构所在地址-纬度值",required = false,dataType = "double",paramType="form"),
            @ApiImplicitParam(name="agencyAddress",value="机构详细地址",required = true,dataType = "String",paramType="form"),
    })
    public R addBaseAgency(@RequestBody BaseAgency insertAgency){
        parameterIsNull(insertAgency.getAgencyType(),"请选择机构类型");
        parameterIsBlank(insertAgency.getAgencyName(),"请填写机构名称");
        if(insertAgency.getAgencyName().length()>80){return R.error(400,"机构名称过长");}
        parameterIsNull(insertAgency.getParentId(),"请选择上级机构");
        parameterIsBlank(insertAgency.getAgencyPhone(),"请填写机构电话");
        parameterIsNull(insertAgency.getAreaGb(),"请选择机构所在区域");
        parameterIsBlank(insertAgency.getAgencyAddress(),"请填写机构详细地址");
//        parameterIsNull(agencyImg,"请上传机构主图");
        if(!PhoneUtils.isPhone(insertAgency.getAgencyPhone()) && PhoneUtils.isTelPhone_(insertAgency.getAgencyPhone())){
            return R.error(400,"机构联系电话格式有误");
        }
        if(insertAgency.getAgencyName().length()>100){
            return R.error(400,"机构名称内容过长");
        }
        if(insertAgency.getAgencyAddress().length()>250){
            return R.error(400,"机构详细地址信息内容过长");
        }
        if(StringUtils.isBlank(insertAgency.getAgencyImg())){
            insertAgency.setAgencyImg("");
        }
        BaseAgency parentAgency = baseAgencyService.selectById(insertAgency.getParentId());
        if(parentAgency==null){
            return R.error(400,"未查询到上级机构信息");
        }
        // 判断 机构类型 和 上级机构类型 匹配
        if( !judgeAgencyType( insertAgency.getAgencyType() , parentAgency.getAgencyType() ) ){
            return R.error(400,"机构类型与上级机构匹配出错");
        }
        AreaCn agencyArea= areaCnService.selectOne(new EntityWrapper<AreaCn>().eq("county_gb",insertAgency.getAreaGb()));
        if(agencyArea==null){
            return R.error(400,"未查询到区域地址信息");
        }
        int countAgencyName = baseAgencyService.selectCount(new EntityWrapper<BaseAgency>().eq("area_gb",insertAgency.getAreaGb()).eq("agency_name",insertAgency.getAgencyName()));
        if(countAgencyName>0){
            return R.error(400,"该机构名称已被使用,请更换");
        }
//        BaseAgency insertAgency = new BaseAgency();
        insertAgency.setAgencyId(BaseModel.returnStaticIdLong());
        insertAgency.setAgencyState(1);//机构默认启用状态
        insertAgency.setLevel(parentAgency.getLevel()+1);
        insertAgency.setCreateTime(new Date());
//        insertAgency.setCreateBy(userId);//设置机构添加人
        baseAgencyService.insert(insertAgency);
        return  R.ok();
    }

    /**
     * 修改机构
     * @return
     */
    @PostMapping("/edit")
    @ApiOperation("修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name="agencyId",value="机构id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="agencyName",value="机构名称",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="agencyType",value="机构类型",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="parentId",value="上级机构id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="agencyPhone",value="机构电话",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="agencyImg",value="机构主图",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="areaGb",value="机构所在地址区编码",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="areaLongitude",value="机构所在地址-经度值",required = false,dataType = "double",paramType="form"),
            @ApiImplicitParam(name="areaLatitude",value="机构所在地址-纬度值",required = false,dataType = "double",paramType="form"),
            @ApiImplicitParam(name="agencyAddress",value="机构详细地址",required = false,dataType = "String",paramType="form"),
    })
    public R editBaseAgency(@RequestBody BaseAgency editAgency){
        parameterIsNull(editAgency.getAgencyId(),"请选择要修改的机构");
        BaseAgency oldAgency = baseAgencyService.selectById(editAgency.getAgencyId());
        if(oldAgency==null){
            return R.error(400,"未查询到机构信息");
        }
        boolean editAgencyTag = false;
        //如果修改机构类型，上级机构必传
        if(editAgency.getAgencyType()!=null){
            parameterIsNull(editAgency.getParentId(),"请选择上级机构");
        }
        // 验证上级机构
        if(editAgency.getParentId()!=null){
            BaseAgency parentAgency = baseAgencyService.selectById(editAgency.getParentId());
            if(parentAgency==null){
                return R.error(400,"未查询到上级机构信息");
            }
            if(editAgency.getAgencyType()==null){
                editAgency.setAgencyType(oldAgency.getAgencyType());
            }
            // 判断 机构类型 和 上级机构类型 匹配
            if( !judgeAgencyType( editAgency.getAgencyType() , parentAgency.getAgencyType() ) ){
                return R.error(400,"机构类型与上级机构匹配出错");
            }
            //判断上级机构 是否修改，同步修改机构level
            if(oldAgency.getParentId()!=editAgency.getParentId()){
                editAgencyTag = true;
                editAgency.setLevel(parentAgency.getLevel()+1);
            }
            //修改机构类型 是否修改
            if(oldAgency.getAgencyType() !=editAgency.getAgencyType()){
                editAgencyTag = true;
            }
        }
        // 判断 机构区域编号 是否修改
        if(editAgency.getAreaGb()!=null&& editAgency.getAreaGb()!=oldAgency.getAreaGb()){
            AreaCn agencyArea= areaCnService.selectOne(new EntityWrapper<AreaCn>().eq("county_gb",editAgency.getAreaGb()));
            if(agencyArea==null){
                return R.error(400,"未查询到区域地址信息");
            }
            editAgencyTag = true;
        }
        //判断 机构名称 修改
        if(StringUtils.isNotBlank( editAgency.getAgencyName() )&& ! oldAgency.getAgencyName().equals(editAgency.getAgencyName())){
            if(editAgency.getAgencyName().length()>80){
                return R.error(400,"机构名称过长");
            }
            if(editAgency.getAreaGb()==null){
                editAgency.setAreaGb(oldAgency.getAreaGb());
            }
            int countAgencyName = baseAgencyService.selectCount(new EntityWrapper<BaseAgency>().eq("area_gb",editAgency.getAreaGb()).eq("agency_name",editAgency.getAgencyName()));
            if(countAgencyName>0){
                return R.error(400,"该机构名称已被使用,请更换");
            }
            editAgencyTag = true;
        }
        //判断机构图片 是否修改
        if(StringUtils.isNotBlank( editAgency.getAgencyImg() )&& !editAgency.getAgencyImg().equals( oldAgency.getAgencyImg() )){
            editAgencyTag = true;
        }
        //判断机构联系电话修改
        if(StringUtils.isNotBlank( editAgency.getAgencyPhone() )&& !editAgency.getAgencyPhone().equals( oldAgency.getAgencyPhone() )){
            if(!PhoneUtils.isPhone(editAgency.getAgencyPhone()) && PhoneUtils.isTelPhone_(editAgency.getAgencyPhone())){
                return R.error(400,"机构联系电话格式有误");
            }
            editAgencyTag = true;
        }
        //判断 机构详细地址 修改
        if(StringUtils.isNotBlank( editAgency.getAgencyAddress() )&& !editAgency.getAgencyAddress().equals( oldAgency.getAgencyAddress() )){
            if(editAgency.getAgencyAddress().length()>250){
                return R.error(400,"地址信息内容过长");
            }
            editAgencyTag = true;
        }
        if(editAgencyTag){
            baseAgencyService.updateById( editAgency );
        }
        return  R.ok();
    }


    @ApiOperation(value = "禁/启用机构")
    @RequestMapping(value = "/editAgencyState", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "agencyId", value = "机构id", required = false, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "agencyState", value = "机构状态(1-启用，2-禁用)", required = false, dataType = "int", paramType = "form"),
    })
    public R changeAgencyType(Long agencyId,Integer agencyState) {
        parameterIsNull(agencyId, "请选择机构");
        parameterIsNull(agencyState, "机构状态不能为空");
        BaseAgency oldAgency = baseAgencyService.selectById(agencyId);
        if(oldAgency==null){
            return R.error(400,"未查询到机构信息");
        }
        if(agencyState!=1&&agencyState!=2){
            return R.error(400,"机构状态有误");
        }
        oldAgency.setAgencyState(agencyState);
        baseAgencyService.updateById(oldAgency);
        return R.ok();
    }

    @ApiOperation(value = "分页查询机构")
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "请求条数", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageNum", value = "请求页数", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "agencyState", value = "机构状态(1-启用，2-禁用)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "agencyType", value = "机构类型", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "agencyName", value = "机构名称-模糊查询", required = false, dataType = "string", paramType = "form"),
   })
    public R page(int pageSize,int pageNum,Integer agencyState,Integer agencyType,String agencyName) {
        if(pageSize<1){pageSize=1;}
        if(pageSize<1){pageNum=10;}
        Page<BaseAgency> agencyPage = new Page<BaseAgency>(pageNum,pageSize);
        Wrapper<BaseAgency> agencyWp=  new EntityWrapper<BaseAgency>();
        if(agencyType!=null){
            agencyWp.eq("agency_type",agencyType);
        }
        if(agencyState!=null){
            agencyWp.eq("agency_state",agencyState);
        }
        if(StringUtils.isBlank(agencyName)){
            agencyWp.like("agency_name",agencyName);
        }
        Page<BaseAgency> returnPage = baseAgencyService.selectPage(agencyPage,agencyWp);
        return R.ok().put("data",returnPage);
    }
    @ApiOperation(value = "条件查询所有")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "agencyState", value = "机构状态(1-启用，2-禁用)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "agencyType", value = "机构类型", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "agencyName", value = "机构名称-模糊查询", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "underAgencyType", value = "根据子级机构类型查询父机构", required = false, dataType = "int", paramType = "form"),
    })
    public R list(Integer agencyState,Integer agencyType,String agencyName,Integer underAgencyType) {
        Wrapper<BaseAgency> agencyWp=  new EntityWrapper<BaseAgency>();
        if(agencyType!=null){
            agencyWp.eq("agency_type",agencyType);
        }
        if(agencyState!=null){
            agencyWp.eq("agency_state",agencyState);
        }
        if(StringUtils.isBlank(agencyName)){
            agencyWp.like("agency_name",agencyName);
        }
        if(underAgencyType!=null){
            if(underAgencyType==2||underAgencyType==3||underAgencyType==4){
                agencyWp.eq("agency_type",1);
            }
            if(underAgencyType==5){
                agencyWp.eq("agency_type",2);
            }
            if(underAgencyType==6){
                agencyWp.eq("agency_type",3);
            }
        }
        List<BaseAgency> returnList = baseAgencyService.selectList(agencyWp);
        return R.ok().put("data",returnList);
    }
    /**
     * 判断 机构类型 和 上级机构类型  是否匹配
     * @param agencyType
     * @param parentAgencyType
     * @return
     */
    public boolean judgeAgencyType(Integer agencyType,Integer parentAgencyType){
        if(parentAgencyType==null||agencyType==null){
            return false;
        }
        if(parentAgencyType==1){//平台
            if(agencyType==2||agencyType==3||agencyType==4){
                return true;
            }
        }
        if(parentAgencyType==2){// 水司
            if(agencyType==5){//水司分区
                return true;
            }
        }
        if(parentAgencyType==3){// 物业
            if(agencyType==6){//物业社区
                return true;
            }
        }
        if(parentAgencyType==4){//设备厂家
           return false;
        }
        return false;
    }

    /**
     * 判断 机构类型 和 上级机构类型  是否匹配
     * @param agencyType
     * @return
     */
    public int getParentAgencyType(int agencyType){
            if(agencyType==2||agencyType==3||agencyType==4){
                return 1;
            }
            if(agencyType==5){//水司分区
                return 2;
            }
            if(agencyType==6){//物业社区
                return 3;
            }
            return 0;
    }
}